package com.example.springbootdemo.mylist.linkedList;

import com.example.springbootdemo.mylist.MyList;
import com.example.springbootdemo.mylist.MyNode;

/**
 * 要注意的是边界问题
 * @author cici
 */
public class MyLinkList<T> implements MyList {

    /**
     * 链表大小
     */
    private int size;

    /**
     * 头结点
     */
    private MyNode<T> first;

    /**
     * 尾结点
     */
    private MyNode<T> last;

    public void MyLinkList(){
        first = null;
        last = null;
        size = 0;
    }

    @Override
    public boolean add(Object o) {
        return addLast(o);
    }

    private boolean addLast(Object o) {

        if (size == 0){
            MyNode node = new MyNode(null,o,null);
        }else {
            MyNode node = new MyNode(last,o,null);
            last.next = node;
            last = node;
        }
        size ++;
        return true;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        if (size == 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean contains(Object o) {

        if (size == 0){
            return false;
        }
        if(first.item.equals(o)){
            return true;
        }
        MyNode node = new MyNode(null,null,null);
        node = first;
        while (node.next != null){
            if (node.next.item.equals(o)){
                return true;
            }
            node = node.next;
        }
        return false;
    }

    @Override
    public boolean remove(int index) {
        MyNode node = (MyNode) get(index);
        node.prev.next = node.next;
        node.next.prev = node.prev;
        return true;
    }

    @Override
    public boolean clear() {
        first = null;
        last = null;
        return true;
    }

    @Override
    public Object get(int index) {
        for(int i = 1 ; i <= index ; i++){
            MyNode node = new MyNode(null,null,null);
            while(i != index){
                node = node.next;
            }
            return node;
        }
        return null;
    }

}
